/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React from 'react';
import {createRef } from 'react';
import type {PropsWithChildren} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Platform,PermissionsAndroid
} from 'react-native';

import {Colors} from 'react-native/Libraries/NewAppScreen';
import NavBar from './components/NavBar';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import messaging from '@react-native-firebase/messaging';
import JPush from 'jpush-react-native';
import Permissions from 'react-native-permissions';
import firebase from '@react-native-firebase/app';
import { EventEmitter } from 'events';

import JsBook from './pages/JsBook';
import AlgorithmBook from './pages/AlgorithmBook';
import NotificationDetail from './pages/NotificationDetail';
export const navigationRef = createRef();
const navigate = (name, params) => {
  console.log('Attempting to navigate to:', name, 'with params:', params);
  if (navigationRef.current) {
    setTimeout(() => {
      navigationRef.current.navigate(name, params);
    }, 1000);
  } else {
    console.log('Navigation ref is not ready, retrying in 500ms...');
    // 添加重试机制
    setTimeout(() => {
      if (navigationRef.current) {
        navigationRef.current.navigate(name, params);
      } else {
        console.error('Navigation failed after retry');
      }
    }, 1000);
  }
};
const Stack = createNativeStackNavigator();

const checkNotificationPermission = async () => {
  try {
    // iOS 需要请求权限
    if (Platform.OS === 'ios') {
      const authStatus = await messaging().requestPermission();
      const enabled =
        authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
        authStatus === messaging.AuthorizationStatus.PROVISIONAL;

      return enabled;
    } 
    // Android API 级别 33 (Android 13) 及以上需要请求权限
    else if (Platform.OS === 'android' && Platform.Version >= 33) {
      const permission = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
      );
      return permission === PermissionsAndroid.RESULTS.GRANTED;
    }
    // 较低版本的 Android 默认授予权限
    return true;
  } catch (error) {
    console.error('权限检查失败:', error);
    return false;
  }
};

// 请求通知权限
const requestNotificationPermission = async () => {
  try {
    const hasPermission = await checkNotificationPermission();
    if (hasPermission) {
      const token = await getFCMToken();
    }
    return hasPermission;
  } catch (error) {
    console.error('请求权限失败:', error);
    return false;
  }
};

const getFCMToken = async () => {
  try {
    const hasPermission = await checkNotificationPermission();
    
    if (hasPermission) {
      const fcmToken = await messaging().getToken();
      console.log('FCM Token:', fcmToken);
      return fcmToken;
    }
    
    return null;
  } catch (error) {
    console.error('获取 FCM Token 失败:', error);
    return null;
  }
};

const initializeFirebase = async () => {
  try {
    if (!firebase.apps.length) {
      await firebase.initializeApp();
      console.log('Firebase 初始化成功');
    }
  } catch (error) {
    console.error('Firebase 初始化失败:', error);
  }
};

const setupNotifications = async () => {
  // 首先初始化 Firebase
  await initializeFirebase();
  const hasPermission = await requestNotificationPermission();
};



export default class App extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    JPush.init({"appKey":"4fcc3e237eec4c4fb804ad49","channel":"test","production":1});
    JPush.getRegistrationID(result =>
      console.log("registerID:" + JSON.stringify(result))
    );
    JPush.addConnectEventListener(result => {
      console.log('JPush 连接状态:', result);
    });
    //本地通知回调
    JPush.addNotificationListener(message => {
      console.log('本地通知回调收到推送通知aaa:', message);
      if (message.notificationEventType === "notificationOpened") {
        if (message.extras && message.extras.url) {
          console.log('准备导航到URL:', message.extras.url);
          // 添加一小段延时确保导航已经准备好
          setTimeout(() => {
            navigate('notificationDetail', { url: message.extras.url });
          }, 100);
        }
      }
    });
    
    //自定义消息回调
    JPush.addLocalNotificationListener(message => {
      console.log('自定义消息回调收到推送通知:', message);
      
    });
    JPush.initCrashHandler
    //应用内消息回调
    JPush.addCustomMessageListener(message => {
      console.log('应用内消息回调收到自定义消息:', message);
    });
    //应用内消息回调

    //JPush.pageEnterTo("HomePage") // 进入首页，当页面退出时请调用 JPush.pageLeave('HomePage')

    JPush.addInappMessageListener(message => {
      console.log('addInappMessageListener:', message);
    });
    JPush.addTagAliasListener(message => {
      console.log('addTagAliasListener:', message);
    });
    //手机号码事件回调
    JPush.addMobileNumberListener(message => {
      console.log('mobileNumberListener:', message);
    });
  }
  render() {
    return (
      <NavigationContainer ref={navigationRef}>
        <Stack.Navigator initialRouteName="jsBook">
          <Stack.Screen name="jsBook" component={JsBook} />
          <Stack.Screen name="algorithmBook" component={AlgorithmBook} />
          <Stack.Screen name="notificationDetail" component={NotificationDetail} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}

//export default App;
